package com.shipwe.loans.analyse.util

import android.app.Application
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.shipwe.loans.analyse.AnalyseBuilder
import com.shipwe.loans.analyse.bean.GoogleShipweBean
import com.shipwe.loans.utils.log.ShipweLogger

object GoogleShipweUtil {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var _installReferrer: String = ""

    private var _installReferrerClient: InstallReferrerClient? = null

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) {
            saveS2sInfo()
        }
    }

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String) -> Unit) {
        try {
            if (_installReferrer.isBlank()) {
                _installReferrerClient = InstallReferrerClient.newBuilder(context).build()
                _installReferrerClient?.let {
                    it.startConnection(object : InstallReferrerStateListener {
                        override fun onInstallReferrerSetupFinished(responseCode: Int) {
                            when (responseCode) {
                                InstallReferrerClient.InstallReferrerResponse.OK -> {
                                    try {
                                        _installReferrer = it.installReferrer?.installReferrer ?: ""
                                        it.endConnection()

                                        //回调通知
                                        success.invoke(getInstallReferrer())

                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                        it.endConnection()
                                    }
                                }

                                InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                                    ShipweLogger.i("FEATURE_NOT_SUPPORTED")
                                    it.endConnection()
                                }

                                InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                                    ShipweLogger.i("SERVICE_UNAVAILABLE")
                                    it.endConnection()
                                }
                            }
                        }

                        override fun onInstallReferrerServiceDisconnected() {
                        }
                    })
                }
            } else {
                //回调通知
                success.invoke(getInstallReferrer())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取Install Referrer
     */
    fun getInstallReferrer(): String {
        return _installReferrer
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo() {
        val path = AnalyseBuilder.pathGoogleInstall
        val url = UrlHelper.combineUrl()
        val body = GoogleShipweBean(
            channelCode = getInstallReferrer(),
            subChannelCode = getInstallReferrer()
        ).encrypt(path)
        AnalyseRequestUtil.doPostAction(url, body)
    }
}